/**
 * 夜间行车分析
 */
$(function(){
	NightDrivingAna.init();
});

var NightDrivingAna = {
	param: {},
	init: function(){
		var me = this;
		me.myChart=null;
		me.initQueryTime();
		
		me.initEmptyVehicleList();
		me.initVehicleUnitList();
		me.barChart = me.initBarChart();
		me.pieChart = me.initPieChart();
		var startTime=$("#inputStartDate").val();
	   	var endTime=$("#inputEndDate").val();
		me.queryPieChartData("",startTime,endTime,"");
		me.loadTableTitle();
		me.time=[];
		me.speed=[];
		me.initEcharts();
		me.initEvent();
	},
	initEcharts : function(){
		var me=this;
		me.myChart = echarts.init(document.getElementById('speedCharts'));
    	var option = {
    		    xAxis: {
    		    	type : 'category',
    	            boundaryGap : false,
    		        data:me.time 
    		    },
    		    grid:{
    		    	x:30,
    		    	y:30,
    		    	x2:5,
    		    	y2:5
    		    	
    		    },
    		    calculable : true,
    		    tooltip: {
    		        trigger: 'axis',
    		        formatter: function (params) {
    		            params = params[0];
    		            return "时间:"+params.name+"<br/>"+"速度"+params.value;
    		        },
    		        axisPointer: {
    		            animation: false
    		        }
    		    },
    		    yAxis: {
    		        name : '速度(km/h)',
    			    type : 'value',
    			    max : 150,
    			    data : [30,60,90,120,150]
    		    },
    		    series: [
    		        {
    		            name:'速度',
    		            type:'line',
    		            smooth:true,
    		            stack: 'a',
    		            data: [0]
    		        }
    		    ]
    		};
    	me.myChart.setOption(option);
    },
	initEvent: function(){
		var me = this;
		var startTime=$("#inputStartDate").val();
	   	var endTime=$("#inputEndDate").val();
	   	var vehicleId=$("#selectVehicleSel").val();
	   	var unitId=$("#selectVehicleUnitSel").val();
	   	
		me.queryBarChartData(unitId,vehicleId,startTime,endTime);
		me.queryPieChartData(unitId,startTime,endTime,vehicleId);
		$("#queryBtn").click(function(){
			var unitId=$("#selectVehicleUnitSel").val();
			/*if(unitId==''||unitId==null){
				return;
			}*/
			//$("#plateNum").hide();
			var startTime=$("#inputStartDate").val();
		   	var endTime=$("#inputEndDate").val();
		   	var vehicleId=$("#selectVehicleSel").val();
		   	
		   	var end_str = (endTime).replace(/-/g,"/");//一般得到的时间的格式都是：yyyy-MM-dd hh24:mi:ss，所以我就用了这个做例子，是/的格式，就不用replace了。  
	    	var end_date = new Date(end_str);//将字符串转化为时间  
	    	//开始时间  
	    	var sta_str = (startTime).replace(/-/g,"/");  
	    	var sta_date = new Date(sta_str); 
	    	var num = (end_date-sta_date)/(1000*3600*24);//求出两个时间的时间差，这个是天数  
	    	var days = parseInt(Math.ceil(num));//转化为整天（小于零的话剧不用转了） 
	    	if(days>30){
	    		global.ajaxLoading.pop("查询时间不能超过30天",false,2000);
	    		return;
	    	}
	    	
	    	
			me.queryBarChartData(unitId,vehicleId,startTime,endTime);
			me.queryPieChartData(unitId,startTime,endTime,vehicleId);
    	});
		$("#exportExcel").click(function(){
			/*var unitId=$("#selectVehicleUnitSel").val();
			if(unitId==''||unitId==null){
				return;
			}*/
			me.exportExcel();
		});
	},
    initVehicleList:function(unitId){
    	$.ajax({
    		type : 'post',
    		async : false,
    		url : appCtx + "/system/vehicle/queryVehicleByAuthAndUnit.html?unitId="+unitId,
    		cache : false,
    		dataType : "JSON",
    		success : function(data) {			
    			if(data){
    				$('#vehicleSelDiv').html("<select class='query-select' id='selectVehicleSel'></select>");
    				
    				var selectStr="";
    				selectStr+="<option value=''>请选择</option>";
    				$.each(data.vehicleList,function(entryIndex,entry) {
    					selectStr+="<option value='"+entry.vehicleId+"'>"+entry.registrationNO+"</option>";
    				});
    				
    				$('#selectVehicleSel').html(selectStr);
    				
    				$("#selectVehicleSel").select2();

    			}
    		}
    	});
    },
    initEmptyVehicleList: function(){
    	$('#vehicleSelDiv').html("<select class='query-select' id='selectVehicleSel'></select>");
    	var selectStr="";
		selectStr+="<option value=''>请选择</option>";		
		$('#selectVehicleSel').html(selectStr);		
		$("#selectVehicleSel").select2();
    },
    initVehicleUnitList:function(){
    	var me = this;
    	$.ajax({
    		type : 'post',
    		async : false,
    		url : appCtx + "/report/convoyRunning/loadVehicleUnit.html",
    		cache : false,
    		dataType : "JSON",
    		success : function(data) {			
    			if(data){
    				 var selectStr="<option value=''>请选择</option>";
    				for(var i=0;i<data.length;i++){
    					selectStr+="<option value='"+data[i].id+"'>"+data[i].name+"</option>";
    				}
    				$('#selectVehicleUnitSel').html(selectStr);		
    				$("#selectVehicleUnitSel").select2();
    				$("#selectVehicleUnitSel").change(function(){
    					var unitId = $(this).children('option:selected').val(); 
    					if(unitId!=''&&unitId!=null){
    						me.initVehicleList(unitId);
    					}else{
    						me.initEmptyVehicleList();
    					}
    				});
    			}
    		}
    	});
    },
	initBarChart: function(){
		var me = this;
		//计算显示的柱子数
		var percent = 100;

		option = {
		    color: ['#3398DB'],
		    legend: {
                data:['夜间行车次数']
            },
		    tooltip : {
		        trigger: 'axis',
		        show: true,
		        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
		        	show: false,
		            type : 'none'        // 默认为直线，可选为：'line' | 'shadow'
		        },
		        formatter:function(a){
		        	if(a[0].name==''){
		        		return;
		        	}
		        	var relVal = "";
		        	relVal = a[0].name+"："+a[0].value+"次";
		        	return relVal;
		        }
		    },
		    grid: {
		        left: '3px',
		        top:'10%',
		        right: '10px',
		        containLabel: true
		    },
		    xAxis : [
		        {
		            type : 'category',
		            data : [],
		            //name: '车牌',
		            axisTick: {
		                alignWithLabel: true
		            },
		            axisLabel:{
		            	/*rotate: 20,*/
		            	textStyle: {
                            //color: 'blue',
                            //fontFamily: 'sans-serif',
                            fontSize: 10
                            //fontStyle: 'italic',
                            //fontWeight: 'bold'
                        }
		            }
		        }
		    ],
		    yAxis : [
		        {
		            type : 'value',
		            show: true,    //显示纵轴false-不显示，true-显示
		            /*splitLine:{  
			                    　　　　show:false  
			                    　　 },*/  
		            name: '次数'
		            //nameLocation:'end'
		        }
		    ],
		    series : [
		        {
		            name:'夜间行车次数',
		            type:'bar',
		            barWidth: '60%',
		            /*itemStyle: {
		                normal: {
		                    //color: 'tomato',
		                    //barBorderColor: 'tomato',
		                    //barBorderWidth: 6,
		                    //barBorderRadius:0,
		                    label : {
		                        show: true, position: 'insideTop' //柱状图顶部显示数字
		                    }
		                }
		            },*/
		            data:[]
		        }
		    ],
		    dataZoom: [{
		        type: 'inside',
		        start: 0,
		        end: percent
		    }, {
		        start: 0,
		        end: percent,
		        fillerColor:'#A3E1A3',
		        handleColor:'#83A7D1'
		    }]
		};
            var myChart = echarts.init(document.getElementById('barChart'));
            myChart.setOption(option);
            window.onresize = myChart.resize;
            
            myChart.on('click', function(param){
            	var vehicleIdList = me.vehicleIdList;
            	var vehicleId = vehicleIdList[param.dataIndex];
            	me.queryNightDrivingTable(vehicleId,param.name);
            });
            
            return {
            	refash : function(option){
                    myChart.setOption(option);
            	},
            	option : option,
            	barChartDom : myChart
            };
	},
	initPieChart: function(){
		option = {
			    title : {
			        text: '',
			        subtext: '',
			        x:'center',
			        show:false
			    },
			    tooltip : {
			        trigger: 'item',
			        formatter: "{b} : {c}次  ({d}%)"
			       
			    },
			    legend: {
			        orient: 'vertical',
			        left: 'left',
			        data: [],
			        show: false
			    },
			    series : [
			        {
			            name: '',
			            type: 'pie',
			            radius : '75%',
			            center: ['50%', '50%'],
		            	labelLine: {
		                normal: {
		                    show: false
		                }
		            	},
		            	label: {
		                normal: {
		                    show: false
		                }
		            	},
			            data:[],
			            itemStyle: {
			                emphasis: {
			                    shadowBlur: 10,
			                    shadowOffsetX: 0,
			                    shadowColor: 'rgba(0, 0, 0, 0.5)'
			                },
			                normal:{ 
				                  label:{ 
				                    show: true, 
				                    formatter: '{b}({d}%)' 
				                  }, 
				                  labelLine :{show:true} 
				            }
			            }
			             
			        }
			    ],
			    color: ['rgb(255,165,0)','rgb(205,133,63)','rgb(165,42,42)','rgb(255,20,147)','rgb(199,21,133)','rgb(160,32,240)','rgb(139,137,137)','rgb(122,103,238)','rgb(141,182,205)','rgb(139,0,139)','rgb(144,238,144)','rgb(139,0,139)','rgb(238,58,140)','rgb(205,16,118)','rgb(255,114,86)','rgb(139,101,8)','rgb(50,205,50)']
			};
		
		 var myChart = echarts.init(document.getElementById('pieChart'));
         myChart.setOption(option);
         window.onresize = myChart.resize;
         return {
         	refash : function(option){
                 myChart.setOption(option);
         	},
         	option : option,
         	pieChartDom : myChart
         };
	},
	queryBarChartData: function(unitId,vehicleId,startTime,endTime){
		var me = this;
		$.ajax({
			type : 'post',
			async : false,
			url : appCtx+"/report/nightDriving/queryBarChartData.html?unitId="+unitId+"&vehicleId="+vehicleId+"&startTime="+startTime+"&endTime="+endTime,
			cache : false,
			dataType : "JSON",
			success : function(data) {
				var option = me.barChart.option;
				option.xAxis[0].data = data.xAxisData;//['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
				option.series[0].data = data.series;//[10, 52, 200, 334, 390, 330, 220];
				me.barChart.refash(option);
				me.vehicleIdList = data.vehicleIdList;
				
				//默认展示第一个的列表
				me.queryNightDrivingTable(data.vehicleIdList[0],data.xAxisData[0]);
			}
		});
	},
	queryPieChartData: function(unitId,startTime,endTime,vehicleId){
		var me = this;
		$.ajax({
			type : 'post',
			async : false,
			url : appCtx+"/report/nightDriving/queryPieChartData.html?unitId="+unitId+"&startTime="+startTime+"&endTime="+endTime+"&vehicleId="+vehicleId,
			cache : false,
			dataType : "JSON",
			success : function(data) {
				var option = me.pieChart.option;
				if(data.legendData.length==0){
					option.legend.data = [0];
					option.series[0].data = [{'name':'无数据','value':0}];
				}else{
					option.legend.data = data.legendData;
					option.series[0].data = data.series;
				}
				
				me.pieChart.refash(option);
			}
		});
		
	},
    getColumn:function(){
    	return [/*{
            display : '序号',
            name : 'index',
            width : 100,
            sortable : false,
            align : 'left'
        },*/{
            display : '车牌',
            name : 'plateNumber',
            width : 15,
            sortable : false,
            align : 'left',
            showTitle : 'plateNumber'
        },{
            display : '开车时间',
            name : 'startDateTime',
            width : 20,
            sortable : false,
            align : 'left',
            showTitle : 'startDateTime'
        },{
            display : '停车时间',
            name : 'endDateTime',
            width : 20,
            sortable : false,
            align : 'left',
            showTitle : 'endDateTime'
        },{
            display : '开车时长',
            name : 'driveTimeStr',
            width : 13,
            sortable : false,
            align : 'left',
        },{
            display : '开车里程',
            name : 'milegeStr',
            width : 13,
            sortable : false,
            align : 'left'
        },{
        	display : '操作',
            name : 'Handler',
            width : 19,
            sortable : false,
            align : 'center',
            paramcolnames:['vehicleId','startDateTime','endDateTime','isVideo'],
            handlefunction:function(vehicleId,startDateTime,endDateTime,isVideo){
            	var handleStr = "";	
            	if(isVideo==1||isVideo=="1"){
            		handleStr += '<div style="padding:0px;float:left;width:35px;height:19px;cursor:pointer;"><img name="vedioPlayBackBtn" vehicleId="'+vehicleId+'" src="'+global.url.domain+'gps-web/resources/images/video.png" title="视频回放"></div><div style="float: left;margin: 0px;padding: 0px;width: 1px;height: 19px;border: 1px solid #dfdddd;"></div>';  		
            	}
        		handleStr += '<div style="padding:0px;float:left;width:35px;height:19px;cursor:pointer;"><img vehicleId="'+vehicleId+'" startDateTime="'+startDateTime+'" endDateTime="'+endDateTime+'" name="trackPlayBtn" src="'+global.url.domain+'gps-web/resources/images/track.png" title="轨迹显示"><div>';		
        		return handleStr;
            }
        }]
    },
    loadTableTitle:function(){
    	$("#objTable").flexigrid({
	            dataType : 'json',
	            colModel :this.getColumn() ,
	            usepager : false,// 是否分页，默认为true。
	            height:343,
	            widthType:'%',
	            width:$('.detail-report').width(),
	            rp : 100000
	         });	 
    },
    queryNightDrivingTable:function(vehicleId,plateNumber){
    	var startTime=$("#inputStartDate").val();
     	var endTime=$("#inputEndDate").val();
     	
     	var end_str = (endTime).replace(/-/g,"/");//一般得到的时间的格式都是：yyyy-MM-dd hh24:mi:ss，所以我就用了这个做例子，是/的格式，就不用replace了。  
    	var end_date = new Date(end_str);//将字符串转化为时间  
    	//开始时间  
    	var sta_str = (startTime).replace(/-/g,"/");  
    	var sta_date = new Date(sta_str); 
    	var num = (end_date-sta_date)/(1000*3600*24);//求出两个时间的时间差，这个是天数  
    	var days = parseInt(Math.ceil(num));//转化为整天（小于零的话剧不用转了） 
    	if(days>30){
    		global.ajaxLoading.pop("查询时间不能超过30天",false,2000);
    		return;
    	}
    	
    	
    	global.ajaxLoading.pop('正在拼命加载,请稍候!',true);
    	var src = appCtx+"views/business/gis/trackPlayBackCommon.jsp";
 		$("#trackPlayBackIframe").attr('src',src);
        var me = this;
      //  $("#plateNum").show();
	//	$("#plateNum").html(plateNumber);
        
     	var url=appCtx+"/report/nightDriving/queryNightDrivingListByVID.html?vehicleId="+vehicleId+"&startTime="+startTime+"&endTime="+endTime;
     	$.post(url,function(data){
     		if(typeof(data)!="undefined"){
     			var dataList = JSON.parse(data);
		     	var dataRows= {
		     		rows:dataList,
		     		totol:dataList.length,
		     		page:1
		     	};
		     	$("#objTable").flexAddData(dataRows);

		     	//
		     	$("img[name='trackPlayBtn']").bind('click',function(){
		     		var vehicleId = $(this).attr('vehicleId');
		     		var startDateTime = $(this).attr('startDateTime');
		     		var endDateTime = $(this).attr('endDateTime');
//		     		var vehicleId = 122;
//		     		var startDateTime = '2017-06-11 09:30:00';
//		     		var endDateTime = '2017-06-11 11:40:00';
		     		var src = appCtx+"views/business/gis/trackPlayBackCommon.jsp?vehicleId="+vehicleId+"&startTime="+startDateTime+"&endTime="+endDateTime+"";
		     		$("#trackPlayBackIframe").attr('src',src);
		     		$.ajax({
		        		type : 'post',
		        		async : false,
		        		url : appCtx+'gis/playback/queryTrackList.html?vehicleId='+vehicleId+"&startTime="+startDateTime+"&endTime="+endDateTime,
		        		cache : false,
		        		dataType : "JSON",
		        		data:{},
		        		success : function(result) {			
		        			if(result){
		        				for(var i=0;i<result.length;i++){
		        					me.time.push(result[i].gps_time);
			        				me.speed.push(result[i].gps_speed);
		        				}
		        				
		        				me.myChart.setOption({
		                            xAxis: {
		                                data: me.time
		                            },
		                            series: [{
		                                name:'速度',
		                                data: me.speed
		                            }]
		                        });
		        			}
		        		}
		        	});
		     	});
		     	
		     	$("img[name='vedioPlayBackBtn']").bind('click',function(){
		     		var vehicleId = $(this).attr('vehicleId');
		     		var vedioPlayUrl = appCtx + "/video/hisVideo.html?vehicleID="+vehicleId;
		     	 	window.open(vedioPlayUrl,"_blank"); 
		     	});
		     }
     		global.ajaxLoading.close();
     	});
    },
    exportExcel : function(){
    	var me = this;
		var header1 = JSON.stringify(me.getColumn());
		var header2 = JSON.parse(header1);
		
		var headerWidth = $('.detail-report').width();
		for(var i=0;i<header2.length;i++){
			header2[i].width = Math.ceil(headerWidth / 100 * header2[i].width);
		}
		header2.splice(header2.length-1,1);
		var header3 = JSON.stringify(header2);
		 var imageUrl = me.barChart.barChartDom.getDataURL({
			type: 'png',
		    pixelRatio: 1
		}); 
		 
		 var imageUrl2 = me.pieChart.pieChartDom.getDataURL({
				type: 'png',
			    pixelRatio: 1
		}); 
		 
		//表头
		var colModelList=new Array();
		colModelList.push(header3);
		var colModel= $.toJSON(colModelList);
		
		//图片
		var imgsrcList=new Array();
		imgsrcList.push(imageUrl);
		imgsrcList.push(imageUrl2);
		var imgsrc= $.toJSON(imgsrcList);
			
		var param =  {
				startTime:$("#inputStartDate").val()+" 00:00；00",
				endTime: $("#inputEndDate").val()+" 23:59:59",
				vehicleId:$("#selectVehicleSel").val(),
				unitId:$("#selectVehicleUnitSel").val(),
				colModel:colModel,
				title:"夜间行车分析导出",
				imgsrc:imgsrc
		};
		post(appCtx+"report/nightDriving/exportNightDriving.html",param);
		
	},
    initQueryTime:function(){
        var todayDate = new Date();
        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
        //$("#inputEndDate").val(todayDateStr);
        	
        var beforeDate = new Date(todayDate-86400000*1); //前一天
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.length == 1) {
	        dd = '0' + dd;
	    }
        $("#inputStartDate").val(yyyy + '-' + mm + '-' + dd);
        $("#inputEndDate").val(yyyy + '-' + mm + '-' + dd);
      }
};
